package cn.com.callback

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.EliteBean;
import cn.com.elite.PropertiesUtil;
import cn.com.elite.Util;
import java.util.Map;
import java.util.regex.Matcher
import java.util.regex.Pattern
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import net.sf.json.JSONArray;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class SmsGetMoMwzx implements CallBackInvoke{
	private static final Log log=LogFactory.getLog(SmsGetMoMwzx.class);
	public void doCallBack(EliteBean eliteBean,String callBack,Map map,String body){
		log.debug("=========================MWZXGetMo==================");
		PropertiesUtil pt= new PropertiesUtil();
		def timestamp = Util.getNowString("MMddHHmmss");
		def userid = pt.readValue("mwzx_userid"); //短信通道账号
		def pwd = Util.getMD5Str(userid+pt.readValue("sms_str")+pt.readValue("mwzx_pwd")+timestamp); //userid + 固定字符串+ pwd(明文) + 时间戳，再进行MD5加密
		def ipport = pt.readValue("sms_ip")+":"+pt.readValue("mwzx_port"); //短信通道ip+端口
		def url = "http://"+ipport+"/sms/v2/std/get_mo"; //接口请求地址
		def charset = "utf-8"; //设置字符集
		def timeout = 100000; //设置请求超时时间
		def enableSSLflag = 0;
		Map headMap=new HashMap(); //设置头文件
		headMap.put("Content-Type","application/json");
		def i = 0;
		def mobile = "";
		def spno = 0;
		def exno = 0;
		def msg = "";
		def smap = "";
		def sk_invpty = 0;
		def input = "";
		def sqlresult = "";
		def guid = "";
		try {
			JSONObject josnbody = new JSONObject();
			josnbody.put("userid",userid);
			josnbody.put("pwd",pwd);
			josnbody.put("timestamp",timestamp);
			josnbody.put("retsize",200);
			//log.debug("josnbody:"+JSONObject.fromObject(josnbody).toString());
			def msgjson = Util.doHttpPostUseHead(url,JSONObject.fromObject(josnbody).toString(),charset,timeout,enableSSLflag,headMap);
			//log.debug("result:"+msgjson);
			JSONObject obj = JSONObject.fromObject(msgjson);
			if(obj.get("result")==0) {
				JSONArray mos = obj.getJSONArray("mos");
				for (i = 0; i < mos.size(); i++) {
					try {
						JSONObject it = mos.get(i);
						//log.debug("it:"+it);
						mobile = it.get("mobile");
						spno = Util.filterForObject(it.get("spno")).equals("")?0:it.get("spno");
						exno = Util.filterForObject(it.get("exno")).equals("")?0:it.get("exno");
						msg = URLDecoder.decode(it.get("content"), "UTF-8"); //获取短信内容
						guid = Util.getGuid();
						eliteBean.update("insert into sms_getmo(rec_guid,mobile,spno,exno,rtime,msg,pipe)values('"+guid+"','"+mobile+"',"+spno+","+exno+",to_date('"+it.get("rtime")+"','yyyy-mm-dd hh24:mi:ss'),'"+msg+"',2)","dataSource");
						msg = replaceBlank(msg); //去空格去回车符处理						
						if(msg.equals("1") || msg.equals("2") || msg.equals("3")) {
							msg = "0"+msg;
						}else if(msg.equals("t") || msg.equals("td") || msg.equals("TD")|| msg.equals("qxdzsrzf")|| msg.equals("QXDZSRZF") || msg.equals("退订") || msg				.equals("退")) {
							msg = "T";
						};//短信内容规范处理
						if( msg.equals("01") || msg.equals("02") || msg.equals("03")) {
							//smap = eliteBean.chaxun_sql("select sk_invpty,invpty_name,sms_id from sms_send where phone='"+mobile+"' and exno="+exno+"","dataSource");
							
							//判断近10日是否推送  SMS011-首次交易上行短信  SMS087
							smap = eliteBean.chaxun_sql("select sk_invpty,invpty_name,sms_id from sms_send where phone='"+mobile+"' and STIME>=trunc(sysdate-7) and SMS_ID in ('SMS011','SMS087') union select sk_invpty,invpty_name,sms_id from sms_send_his where phone='"+mobile+"' and STIME>=trunc(sysdate-15) and SMS_ID in ('SMS011','SMS087') ","dataSource");

							if(smap.size()==0) {
								continue;
							};
						}else if(msg.equals("T")){//客户退订时，统一取最近一条短信对应模板退订处理
							
							smap = eliteBean.chaxun_sql("select * from sms_send where  SMSNO=(select max(SMSNO) from sms_send where phone='"+mobile+"' and  sms_id is not null)","dataSource");
							log.debug("select * from sms_send where  SMSNO=(select max(SMSNO) from sms_send where phone='"+mobile+"' and  sms_id is not null)");
							if(smap.size()==0) {//当前表无数据再查sms_send_his																
								smap = eliteBean.chaxun_sql("select * from sms_send_his where  SMSNO=(select max(SMSNO) from sms_send_his where phone='"+mobile+"' and  sms_id is not null)","dataSource");	
								
								if(smap.size()==0) {
									continue;
								};		
							};
												
						}
						else{
							continue;
						};
						def sms_id = smap[0].get("sms_id");
						//回复了具体订阅ID，如果下行不是开户上行短信模板的，则终止本次循环
						
						if(
						  //( !sms_id.equals("SMS011") || !sms_id.equals("SMS087") ) && ( msg.equals("01") || msg.equals("02") || msg.equals("03") )  	
							( sms_id!="SMS011" && sms_id!="SMS087" ) && ( msg.equals("01") || msg.equals("02") || msg.equals("03") )  										  
						) {
							//log.debug(" sms_id: "+sms_id , " msg: "+msg);
							//log.debug("sms_id:"+sms_id,"msg:"+msg);
							log.debug("  未   执行 ");
							continue;
						};
						
						log.debug("  已  执行 ");
						input = new String[5];
						input[0] = smap[0].get("sk_invpty");
						input[1] = msg;
						input[2] = smap[0].get("sms_id");
						input[3] = mobile;
						input[4] = smap[0].get("invpty_name");
						sqlresult = eliteBean.executeWithReturn("{call sp_sms_smssubscription(?,?,?,?,?,?)}",input,"dataSource");
						eliteBean.update("update sms_getmo set checkstate=2,checkdesc='系统已自动处理' where rec_guid='"+guid+"'","dataSource");
					}catch(Exception e) {
						log.error("ErrorMessage:",e);
					};
				};
			};
		}catch(Exception e) {
			log.error("ErrorMessage:",e);
		};
	}
	//字符串去空格去回车符处理
	public static String replaceBlank(String str) {
		String dest = "";
		if (str!=null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}
}
